<template>
  <div class="group-user-panel flex_d-column">
    <div class="header padding-10 flex flex_a_i-baseline">
      <div>群成员</div>
      <div class="margin-n-5">·</div>
      <div>{{ count.online }} / {{ count.total }}</div>
    </div>
    <el-scrollbar ref="refScrollbar" class="flex-item_f-1" @scroll="scrollHandle">
      <div ref="refInner" class="padding-n-5">
        <TransitionGroup tag="div" name="move">
          <GroupUser 
            v-for="item in users"
            :key="item.id"
            :avatar="item.avatar"
            :name="item.roomUserNickname || item.nickname"
            :online="item.online"
            @click="clickHandle(item)">
          </GroupUser>
        </TransitionGroup>
        <div class="margin_t-10 width-full height-20" v-show="loading">
          <Loading text="数据加载中"></Loading>
        </div>
      </div>
    </el-scrollbar>
    <ApplyFriendDialog ref="refApplyFriendDialog"></ApplyFriendDialog>
    <GroupManage 
      v-if="active.group && groupOwnerId" 
      :groupId="active.group.id" 
      :ownerId="groupOwnerId">
    </GroupManage>
  </div>
  <!-- 修改者：hacja -->
</template>

<script setup>
import { ref, computed, nextTick, onBeforeMount, watch } from 'vue'
import { useConversationStore, useRoomStore } from '@/stores'
import GroupUser from '../group-user/index.vue'
import GroupManage from '../group-manage/index.vue'
import Loading from '@/components/loading/index.vue'
import ApplyFriendDialog from '@/components/apply-friend-dialog/index.vue'

const conversationStore = useConversationStore()
const roomStore = useRoomStore()

const active = computed(() => conversationStore.active)

const groupOwnerId = computed(() => {
  if (active.value?.group?.ownerId !== undefined) {
    const ownerId = Number(active.value.group.ownerId)
    return !isNaN(ownerId) ? ownerId : null
  }
  if (active.value?.group?.creator_id !== undefined) {
    const creatorId = Number(active.value.group.creator_id)
    return !isNaN(creatorId) ? creatorId : null
  }
  return null
})

const count = computed(() => {
  const result = {
    total: 0,
    online: 0
  }
  if (active.value) {
    const { roomId } = active.value
    const room = roomStore.list.find(room => room.id === roomId)
    if (room) {
      result.total = room.userTotalCount || 0
      result.online = room.userOnlineCount || 0
    }
  }
  return result
})

const room = computed(() => {
  if (active.value) {
    const { roomId } = active.value
    return roomStore.list.find(room => room.id === roomId)
  }
  return null
})

const users = computed(() => {
  if (room.value) {
    const list = [...room.value.users]
    return list.sort((a, b) => {
      return b.online - a.online
    })
  }
  return []
})

const loading = ref(false)
const finished = ref(false)

const getCount = async () => {
  if (!active.value?.roomId) return
  try {
    await roomStore.getUserCount(active.value.roomId)
  } catch (error) {
    console.error('获取群成员统计失败:', error)
  }
}

const getData = async () => {
  if (!room.value || loading.value || finished.value) return
  
  loading.value = true
  try {
    const { id, users } = room.value
    let lastId = ''
    const length = users.length
    if (length) {
      lastId = users[length - 1].roomUserId
    }

    const list = await roomStore.getUserList(id, lastId)
    if (!list || list.length === 0) {
      finished.value = true
    }
  } catch (error) {
    console.error('获取群成员列表失败:', error)
  } finally {
    loading.value = false
  }
}

const refScrollbar = ref()
const refInner = ref()
const scrollHandle = ({ scrollTop }) => {
  if (!refInner.value || !refScrollbar.value?.wrapRef) return
  
  const height = refInner.value.clientHeight - refScrollbar.value.wrapRef.clientHeight
  if (scrollTop >= height * 0.8 && !loading.value && !finished.value) {
    getData()
  }
}

const refApplyFriendDialog = ref()
const clickHandle = ({ id }) => {
  refApplyFriendDialog.value.open(id)
}

const resetState = () => {
  finished.value = false
  loading.value = false
  // 使用store方法清空用户列表
  if (active.value?.roomId) {
    roomStore.clearRoomUsers(active.value.roomId)
  }
}

watch(() => active.value?.roomId, async (newRoomId, oldRoomId) => {
  if (newRoomId && newRoomId !== oldRoomId) {
    resetState()
    await getCount()
    getData()
  }
})

onBeforeMount(async () => {
  if (active.value?.roomId) {
    resetState()
    await getCount()
    getData()
  }
})
</script>

<style lang="scss" scoped>
.group-user-panel {
  background-color: var(--card-background-color);
  border-radius: var(--box-border-radius);
  .header {
    font-size: 12px;
    border-bottom: 1px solid var(--wrap-background-color);
  }
}
</style>
